<?php


namespace app\api\controller;

use PayPal\Api\Payer;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Details;
use PayPal\Api\Amount;
use PayPal\Api\Transaction;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Payment;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Exception\PayPalConnectionException;
use PayPal\Rest\ApiContext;
use PayPal\Api\PaymentExecution;

use app\common\controller\Api;
use addons\litestore\model\Litestoreorder;
use think\Db;

/**
 * 支付接口
 * Class Pay
 * @package app\api\controller
 */
class Pay extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    const clientId = 'AfC2K2gRgUfzK9843NZO0qj7jO8tKcYV2gfg-eSrC5PPoWiGIL_pXjupOP9QRG_O9fG2prxtYnqGOtil';//ID
    const clientSecret = 'EFYFURzOu_lcQo5DC1_EyKCzxMwaZvv4jSVqyU_wP9J-qdjWEvoCnMzV0up4q5iNoKepvowPzqIcv-vb';//秘钥
    const mode = 'sandbox';//测试

    protected $accept_url = '';//回调地址

    const Currency = 'USD';//币种

    protected $PayPal;

    public function __construct()
    {
        $this->accept_url = request()->domain().'/api.php/api/pay/Callback';//回调地址

        //从后台配置中获取账号信息
        $config = Db::name('pay_method')->where('id',1)->value('config');
        $config = json_decode($config,true);
        $this->PayPal = new ApiContext(
            new OAuthTokenCredential(
                $config['clientId'],
                $config['clientSecret']
            )
        );

        $this->PayPal->setConfig(
            array(
                'mode' => $config['mode'],
                'http.ConnectionTimeOut' => 30,
            )
        );
    }

    //测试
    public function index()
    {
        $product = input('product');
        if (empty($product)) {
            return json(['status' => false, 'msg' => '商品不能为空']);
        }

        $price = input('price');
        if (empty($price)) {
            return json(['status' => false, 'msg' => '价格不能为空']);
        }

        $shipping = input('shipping', 0);


        $description = input('description');
        if (empty($description)) {
            return json(['status' => false, 'msg' => '描述内容不能为空']);
        }

        $order_no = '2023031013402562222';
        $this->pay($order_no,$product, $price, $shipping, $description);
    }

    /**
     * @param
     * $order_no 订单号
     * $product 商品
     * $price 价钱
     * $shipping 运费
     * $description 描述内容
     */
    public function pay($order_id,$order_no,$product, $price, $shipping = 0, $description='')
    {
        $paypal = $this->PayPal;

        $total = $price + $shipping;//总价

        $payer = new Payer();
        $payer->setPaymentMethod('paypal');

        $item = new Item();
        $item->setName($product)->setCurrency(self::Currency)->setQuantity(1)->setPrice($price);

        $itemList = new ItemList();
        $itemList->setItems([$item]);

        $details = new Details();
        $details->setShipping($shipping)->setSubtotal($price);

        $amount = new Amount();
        $amount->setCurrency(self::Currency)->setTotal($total)->setDetails($details);

        $transaction = new Transaction();
        $transaction->setAmount($amount)->setItemList($itemList)->setDescription($description)->setInvoiceNumber($order_no);

        $redirectUrls = new RedirectUrls();
//        $accept_url = request()->domain() .'/#/orderDetail/'.$order_id;
        $accept_url = $this->accept_url;
        $redirectUrls->setReturnUrl($accept_url . '?order_id='.$order_id.'&success=true')->setCancelUrl($accept_url . '/?order_id='.$order_id.'&success=false');

        $payment = new Payment();
        $payment->setIntent('sale')->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions([$transaction]);

        try {
            $payment->create($paypal);
        } catch (PayPalConnectionException $e) {
            return ['code'=>0,'data'=>$e->getData()];
//            echo $e->getData();
//            die();
        }

        $approvalUrl = $payment->getApprovalLink();
        return ['code'=>1,'data'=>$approvalUrl];
    }
    /**
     * 回调
     */
    public function Callback()
    {
        writelog('Callback', $_REQUEST);
        $success = trim($_GET['success']);

        if ($success == 'false' && !isset($_GET['paymentId']) && !isset($_GET['PayerID'])) {
            $web_url = request()->domain() .'/#/orderDetail/'.$_GET['order_id'].'?state=CancelPayment';//取消付款
            header('Location: '.$web_url);
            exit();
        }

        $paymentId = trim($_GET['paymentId']);
        $PayerID = trim($_GET['PayerID']);

        if (!isset($success, $paymentId, $PayerID)) {
            $web_url = request()->domain() .'/#/orderDetail/'.$_GET['order_id'].'?state=PaymentFailed';//支付失败
            header('Location: '.$web_url);
            exit();
        }

        if ((bool)$_GET['success'] === 'false') {
            writelog('Callback', '支付失败，支付ID【' . $paymentId . '】,支付人ID【' . $PayerID . '】');

            $web_url = request()->domain() .'/#/orderDetail/'.$_GET['order_id'].'?state=PaymentFailed';//支付失败
            header('Location: '.$web_url);
            exit();
        }

        $payment = Payment::get($paymentId, $this->PayPal);

        $execute = new PaymentExecution();

        $execute->setPayerId($PayerID);

        try {
            $payment->execute($execute, $this->PayPal);
        } catch (Exception $e) {
            writelog('Callback', $e . ',支付失败1，支付ID【' . $paymentId . '】,支付人ID【' . $PayerID . '】');

            $web_url = request()->domain() .'/#/orderDetail/'.$_GET['order_id'].'?state=PaymentFailed';//支付失败
            header('Location: '.$web_url);
            exit();
        }
        writelog('Callback', '支付成功，支付ID【' . $paymentId . '】,支付人ID【' . $PayerID . '】');

        //处理相关业务
        $order = (new Litestoreorder())->payDetailById($_GET['order_id']);
        if (empty($order)) { // 如果订单不存在
            writelog('Callback',"支付成功，查询订单失败，状态未修改");
        }
        $order->updatePayStatus($paymentId,'paypal');
        
        $web_url = request()->domain() .'/#/orderDetail/'.$_GET['order_id'].'?state=PaymentSucceeded';
        header('Location: '.$web_url);
        exit();
    }
    //异步回调
    public function notify(){
        //获取回调结果
        $json_data = $this->get_JsonData();
        if(!empty($json_data)){
            writelog('notify',"paypal异步通知:\r\n".json_encode($json_data));
        }else{
            writelog('notify',"paypal异步通知失败:参加为空");
        }
        //自己打印$json_data的值看有那些是你业务上用到的
//        halt($json_data);
        if(isset($json_data['resource']['invoice_number'])){
            $order_no = $json_data['resource']['invoice_number'];
        }else{
            $order_no = $json_data['resource']['transactions'][0]['invoice_number'];
        }
        $transaction_id = $json_data['resource']['id'];

        //处理相关业务
        $order = (new Litestoreorder())->payDetail($order_no);
        if (empty($order)) { // 如果订单不存在
            writelog('notify',"订单不存在");
//            return "success";
            abort(200, __('Pay Success'));
        }

        $order->updatePayStatus($transaction_id,'paypal');
        writelog('notify',"支付成功");
//        return "success";
        abort(200, __('Pay Success'));
    }
    public function get_JsonData(){
        $json = file_get_contents('php://input');
        if ($json) {
            $json = str_replace("'", '', $json);
            $json = json_decode($json,true);
        }
        return $json;
    }
    //退款
    public function returnMoney()
    {

        try {
            $txn_id = "xxxxxxx";  //异步回调中拿到的id
            $amt = new Amount();
            $amt->setCurrency('USD')
                ->setTotal('99');  // 退款的费用

            $refund = new Refund();
            $refund->setAmount($amt);

            $sale = new Sale();
            $sale->setId($txn_id);

            $refundedSale = $sale->refund($refund, $this->PayPal);
        } catch (\Exception $e) {
            // PayPal无效退款
            return json_decode(json_encode(['message' => $e->getMessage(), 'code' => $e->getCode(), 'state' => $e->getMessage()]));  // to object
        }
        // 退款完成
        return $refundedSale;
    }
}